Java编程题-使用数组模拟栈

栈:后进先出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Stack类
public class Stack {
// 使用数组存储数据
Object[] elements;

// 指向栈顶元素上方的一个帧
int index;

// 栈默认的初始化容量是5
Stack() {
this(2);
}

Stack(int max) {
elements = new Object[max];
}

// 压栈方法
public void push(Object element) throws StackOperationException {
if (index == elements.length) {
throw new StackOperationException("栈已满");
}
elements[index++] = element;
}

// 弹栈方法
public Object pop() throws StackOperationException {
if (index == 0) {
throw new StackOperationException("栈已空!");
}
return elements[--index];
}
}

// 异常类
public class StackOperationException extends Exception {
public StackOperationException() {
}

public StackOperationException(String msg) {
super(msg);
}
}

// 测试类
public class StackTest {
public static void main(String[] args) {
Stack s = new Stack();

User u1 = new User("Jack", 20);
User u2 = new User("Zhang", 21);
User u3 = new User("Li", 22);

// 压栈
try {
s.push(u1);
s.push(u2);
s.push(u3);
} catch (StackOperationException e) {
e.printStackTrace();
}

// 弹栈
try {
System.out.println(s.pop());
System.out.println(s.pop());
// System.out.println(s.pop());
} catch (StackOperationException e) {
e.printStackTrace();
}
}
}

class User {
String name;
int age;

User(String name, int age) {
this.name = name;
this.age = age;
}

public String toString() {
return "User[name=" + name + ",age=" + age + "]";
}
}